package cn.meizhu.user.service.impl;

import cn.meizhu.base.canstant.WxCanstant;
import cn.meizhu.base.exception.Exceptions;
import cn.meizhu.base.service.impl.BaseServiceImpl;
import cn.meizhu.user.domain.LoginInfo;
import cn.meizhu.user.domain.User;
import cn.meizhu.user.domain.WxUser;
import cn.meizhu.user.domain.tro.UserDto;
import cn.meizhu.user.mapper.LoginInfoMapper;
import cn.meizhu.user.mapper.UserMapper;
import cn.meizhu.user.mapper.WxUserMapper;
import cn.meizhu.user.service.IUserService;
import cn.meizhu.user.service.IWxUserService;
import cn.meizhu.util.AjaxResult;
import cn.meizhu.util.HttpClientUtils;
import cn.meizhu.util.MD5Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.nio.ch.Secrets;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class WxUserServiceImpl extends BaseServiceImpl<WxUser> implements IWxUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Override
    public AjaxResult index(Map<String, String> map) {
        //发送请求，获取access_token
        String code = map.get("code");
        //发送请求
        String url = WxCanstant.ACCESS_TOKEN_URL
                .replace("APPID",WxCanstant.APPID)
                .replace("SECRET",WxCanstant.SECRET)
                .replace("CODE",code);
        String result = HttpClientUtils.httpGet(url);
        //格式化json
        JSONObject jsonObject = JSON.parseObject(result);
        //取值
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        WxUser wxUser = wxUserMapper.findByopenid(openid);
        if (wxUser != null){
            //微信用户关联用户
            User user = userMapper.findById(wxUser.getUser_id());
            LoginInfo loginInfo = loginInfoMapper.findById(user.getLogininfo_id());
            //老用户免密登录
            return noSecrets(loginInfo);
        }else {
            //新用户
            String redirectUri = "/binder.html?access_token="+access_token+"&openid="+openid;
            return AjaxResult.me().setSuccess(false).setResultObj(redirectUri);
        }
    }

    @Override
    @Transactional
    public AjaxResult binder(Map<String, String> map) {
        String phone = map.get("phone");
        String codeType = map.get("codeType");
        String code = map.get("code");
        String access_token = map.get("access_token");
        String openid = map.get("openid");
        //验证验证码是否正确
        String o = (String) redisTemplate.opsForValue().get(phone + ":" + codeType);
        if (o == null){
            return AjaxResult.me().setMessage("验证码输入有误");
        }
        if (!o.split(":")[0].equals(code)){
            return AjaxResult.me().setMessage("验证码输入有误");
        }
        //获取微信个人信息
        String url = WxCanstant.WXUSER_INFO
                .replace("ACCESS_TOKEN",access_token)
                .replace("OPENID",openid);
        System.out.println(url);
        String result = HttpClientUtils.httpGet(url);
        System.out.println(result);
        JSONObject jsonObject = JSON.parseObject(result);
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        //查询改手机号是否注册
        User user = userMapper.findByPhone(phone);
        LoginInfo loginInfo = null;
        if (user ==null){
            user = new User();
            user.setUsername(jsonObject.getString("nickname"));
            user.setPhone(phone);
            user.setCreatetime(new Date());
            user.setState(1);
            user.setHeadImg(jsonObject.getString("headimgurl"));
            loginInfo = new LoginInfo();
            BeanUtils.copyProperties(user,loginInfo);
            loginInfo.setType(1);
            loginInfo.setDisable(1);
            loginInfoMapper.save(loginInfo);
            System.out.println(loginInfo);
            user.setLogininfo_id(loginInfo.getId());
            userMapper.save(user);
            System.out.println(user);
        }else {
            //获取用户对应的LoginInfo
            loginInfo = loginInfoMapper.findById(user.getLogininfo_id());
        }
        wxUser.setUser_id(user.getId());
        wxUserMapper.save(wxUser);
        System.out.println(wxUser);
        //免密登录
        return noSecrets(loginInfo);

    }

    //免密登录
    private AjaxResult noSecrets(LoginInfo loginInfo){
        //生成token
        String token = UUID.randomUUID().toString();
        //把token放到Redis中
        redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
        //把token和loginInfo返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //清空敏感数据
        loginInfo.setPassword("");
        loginInfo.setSalt("");
        map.put("loginInfo",loginInfo);
        return AjaxResult.me().setResultObj(map);
    }
}
